﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LongestSequence.Question;


namespace LongestSequence.Answer
{
   public class Jimson : ILongestSequence
    {
        public int GetLongestSequence(int[] Array)
        {
            List<int> list = new List<int>();
            int MaxLen = 0;
            int Len = 0;
            for (int j = 0; j < Array.Length; j++)
            {
                for (int i = j; i < Array.Length; i++)
                {
                    if (Array[i] != 0 && Array[j] != 0)
                    {
                        if (Math.Abs(Array[i] - Array[j]) > Array.Length)
                        {
                            Len = i - j;
                            break;
                        }
                        else
                        {
                            list.Add(Array[i]);
                        }
                    }
                    else
                    {
                        list.Add(Array[i]);
                    }

                }
                Len = GetMax(list);
                MaxLen = (MaxLen > Len) ? MaxLen : Len;
                list.Clear();
            }

            return MaxLen;
        }

        private int IsSequence(List<int> list)
        {
            if (list == null || list.Count < 1) return -1;
            
            int zerocount = list.Where(l => l == 0).Count();
            
            List<int> a = list.Where(l => l != 0).ToList<int>();
            a.Sort();
            if (a.Count > 0)
            {
                if (Math.Abs(a.Last() - a.First()) <= list.Count())
                {
                    int sum = 0;
                    for (int i = 0; i < a.Count - 1; i++)
                    {
                        sum += Math.Abs(a[i] - a[i + 1]) - 1;
                    }
                    if (sum <= zerocount)
                        return list.Count;
                    else
                        return -1;
                }
                else
                    return -1;
            }
            else 
                return list.Count;
           
        }

       private int GetMax(List<int> list)
       {
           int maxLen = -1;
           int len = -1;

           List<int> templist = new List<int>();
           for (int i = 0; i < list.Count; i++)
           {
               for (int j = 0; j <= i; j++)
               {
                   templist.Add(list[j]);
               }

               len = IsSequence(templist);
               maxLen = (maxLen > len) ? maxLen : len;
               templist.Clear();
           }


           return maxLen;

       }
    }
}
